<template>
	<el-card class="layout-query">
		<el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
			<el-form-item label="关键词" prop="likeNameOrNumber">
				<el-input v-model="state.queryForm.likeNameOrNumber" placeholder="请输入" clearable></el-input>
			</el-form-item>
			<el-form-item label="发布日期" prop="date">
				<el-date-picker
					v-model="state.date"
					type="daterange"
					value-format="YYYY-MM-DD"
					format="YYYY-MM-DD"
					nge-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期"
					clearable
				/>
			</el-form-item>
			<el-form-item label="填报状态" prop="applyStatus">
				<el-select v-model="state.queryForm.applyStatus" placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in applyStatus" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="发布状态" prop="publishStatus">
				<el-select v-model="state.queryForm.publishStatus" placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in publishStatus" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button icon="Search" type="primary" @click="search()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button icon="RefreshRight" @click="reset()">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card>
	<el-card>
		<el-space style="width: 100%; justify-content: flex-end">
			<el-space v-auth="'M004_A'">
				<el-button type="primary" @click="kadd">新增</el-button>
			</el-space>
			<el-space v-auth="'M004_Publish'">
				<el-button :disabled="!hasPublishPermission" type="primary" @click="handleBatchSend">发布</el-button>
			</el-space>
			<el-space v-auth="'M004_CancelPublish'">
				<el-button :disabled="!hasCanclePermission" type="primary" @click="handleBatchCancel">取消发布</el-button>
			</el-space>
		</el-space>

		<el-table
			ref="multipleTableRef"
			v-loading="state.dataListLoading"
			:data="state.dataList"
			class="mt15"
			stripe
			element-loading-background="rgba(0, 0, 0, 0.5)"
			element-loading-text="加载中..."
			header-row-class-name="table-header"
			@selection-change="handleSelectionChange"
		>
			<el-table-column type="selection" width="55" fixed="left" />
			<el-table-column type="index" label="序号" align="center" width="55" fixed="left" />
			<el-table-column label="宣贯名称" align="center" prop="trainingName" width="150" />
			<el-table-column label="标准编号" align="center" prop="standardNumber" width="100"> </el-table-column>
			<el-table-column label="发布日期" align="center" prop="publishTime" width="100"> </el-table-column>
			<el-table-column label="培训文件" align="center" prop="trainingFileId">
				<template #default="scope">
					<div style="color: #1491ff; cursor: pointer" @click="showFileOne(scope.row.trainingFileId)">{{ showFile(scope.row, 0) }}</div>
				</template>
			</el-table-column>
			<el-table-column label="培训视频" align="center" prop="trainingVideoFileId">
				<template #default="scope">
					<div style="color: #1491ff; cursor: pointer" @click="showFileOne(scope.row.trainingVideoFileId)">{{ showFile(scope.row, 2) }}</div>
				</template>
			</el-table-column>
			<el-table-column label="培训内容" align="center" prop="traingContent" width="200">
				<template #default="{ row }">
					<el-tooltip
						effect="dark"
						:content="row.traingContent"
						placement="top"
						popper-class="custom-tooltip"
						:disabled="!isContentOverflow(row.traingContent)"
					>
						<div class="truncate-text">{{ formatContent(row.traingContent) }}</div>
					</el-tooltip>
				</template>
			</el-table-column>
			<el-table-column label="填报状态" align="center" prop="applyStatus" width="120">
				<template #default="scope">
					<span>{{ dictionaryStore.getDictionaryName('T0031', scope.row.applyStatus) }}</span>
				</template>
			</el-table-column>
			<el-table-column label="发布状态" align="center" prop="publishStatus" width="100">
				<template #default="scope">
					<span>{{ dictionaryStore.getDictionaryName('T0032', scope.row.publishStatus) }}</span>
				</template>
			</el-table-column>

			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="130">
				<template #default="scope">
					<el-icon
						v-if="
							Number(scope.row.applyStatus) == 0 &&
							(userStore.user.roleCode.includes('SB') || userStore.user.roleCode.includes('SYADMIN') || userStore.user.roleCode.includes('ZZADMIN'))
						"
						v-auth="'M004_U'"
						:size="16"
						color="#1491FF"
						title="编辑"
						style="cursor: pointer; margin: 0 6px"
						@click="showDetail(scope.row, false)"
					>
						<Edit />
					</el-icon>

					<el-icon
						v-if="
							userStore.user.roleCode.includes('ZZ') &&
							Number(scope.row.publishStatus) == 0 &&
							Number(scope.row.applyStatus) > 0 &&
							Number(scope.row.applyStatus) < 2
						"
						v-auth="'M004_U'"
						:size="16"
						color="#1491FF"
						title="审核"
						style="cursor: pointer; margin: 0 6px"
						@click="showDetail(scope.row, false)"
					>
						<Compass />
					</el-icon>
					<el-icon
						v-if="Number(scope.row.applyStatus) > 0"
						:size="16"
						color="#1491FF"
						title="查看"
						style="cursor: pointer; margin: 0 6px"
						@click="showDetail(scope.row, true)"
					>
						<View />
					</el-icon>
					<el-icon
						v-if="Number(scope.row.applyStatus) == 1"
						v-auth="'M004_Return'"
						:size="16"
						color="#1491FF"
						title="补正(退回)"
						style="cursor: pointer; margin: 0 6px"
						@click="handleApproval(scope.row)"
					>
						<RefreshLeft />
					</el-icon>
					<el-icon
						v-if="Number(scope.row.applyStatus) == 0"
						:size="16"
						color="#fe6360"
						title="删除"
						style="cursor: pointer; margin: 0 6px"
						@click="handleDelete(scope.row.id)"
					>
						<Delete />
					</el-icon>

					<el-icon
						v-if="Number(scope.row.publishStatus) == 0 && Number(scope.row.applyStatus) == 2"
						v-auth="'M004_Publish'"
						:size="16"
						color="#1491FF"
						title="发布"
						style="cursor: pointer; margin: 0 6px"
						@click="handleSend(scope.row.id)"
					>
						<CircleCheck />
					</el-icon>

					<el-icon
						v-if="Number(scope.row.publishStatus) == 1"
						v-auth="'M004_CancelPublish'"
						:size="16"
						color="#1491FF"
						title="取消发布"
						style="cursor: pointer; margin: 0 6px"
						@click="handleCancel(scope.row.id)"
					>
						<CircleClose />
					</el-icon>
				</template>
			</el-table-column>
		</el-table>

		<el-pagination
			:current-page="state.queryForm.pageNum"
			:page-size="state.queryForm.pageSize"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
		>
		</el-pagination>
	</el-card>

	<addtrain ref="updateDetailRef" :is-view="isView" @refresh-data-list="getDataList"></addtrain>
</template>
<script setup lang="ts">
import { approvalApi, cancelPublishApi, deleteApi, listApplyStatusApi, publishApi, queryDataListApi } from '@/api/standardapplication/index'
import { filePreviewByName } from '@/api/sys/upload'
import { useDictionaryStore } from '@/store/modules/dictionary'
import { useUserStore } from '@/store/modules/user'
import { ElMessage, ElMessageBox, ElTable, TableInstance } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import addtrain from './components/addtrain.vue'
const dictionaryStore = useDictionaryStore()
const userStore = useUserStore()

const applyStatus = dictionaryStore.getDictionaryByCode('T0031')
const publishStatus = dictionaryStore.getDictionaryByCode('T0032')
const addtrainvisible = ref(false)

const state = reactive({
	queryForm: {
		pageNum: 1,
		pageSize: 10,
		likeNameOrNumber: '',
		startPublishTime: '',
		endPublishTime: '',
		applyStatus: '',
		publishStatus: ''
	},
	total: 1,
	dataListLoading: false,
	dataList: [],
	ids: [],
	date: []
})
const updateDetailRef = ref()
const multipleTableRef = ref<TableInstance>()

const isView = ref(false)
const hasPublishPermission = computed(() => {
	if (!multipleTableRef.value) {
		return false
	}
	const selectedRows = multipleTableRef.value.getSelectionRows()

	if (selectedRows.length === 0) {
		return false
	}

	const allPermissionValid = selectedRows.every(row => Number(row.publishStatus) == 0 && Number(row.applyStatus) == 2)

	return allPermissionValid
})
const hasCanclePermission = computed(() => {
	if (!multipleTableRef.value) {
		return false
	}
	const selectedRows = multipleTableRef.value.getSelectionRows()

	if (selectedRows.length === 0) {
		return false
	}

	const allPermissionValid = selectedRows.every(row => Number(row.publishStatus) == 1)

	return allPermissionValid
})

const showDetail = (row: any, view: boolean) => {
	isView.value = view
	addtrainvisible.value = true
	updateDetailRef.value.init(false, row)
}
function kadd() {
	addtrainvisible.value = true
	updateDetailRef.value.init(true, {})
}

const isContentOverflow = (content: String) => {
	return content.split('\n').length > 5
}
const formatContent = (content: String) => {
	return content.split('\n').slice(0, 5).join('\n')
}
const handleCancel = (id: Number | String) => {
	let params = {
		ids: [id]
	}
	ElMessageBox.confirm('确定取消发布吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		cancelPublishApi(params).then(res => {
			ElMessage({
				type: 'success',
				message: '取消发布成功'
			})
			getDataList()
		})
	})
}
const handleSend = (id: Number | String) => {
	let params = {
		ids: [id]
	}

	ElMessageBox.confirm('确定发布吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		publishApi(params).then(res => {
			ElMessage({
				type: 'success',
				message: '发布成功'
			})
			getDataList()
		})
	})
}

const handleBatchSend = () => {
	const selectedRows = multipleTableRef.value.getSelectionRows()
	const ids = selectedRows.map(row => row.id)
	let params = {
		ids: ids
	}

	ElMessageBox.confirm('确定发布吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		publishApi(params).then(res => {
			ElMessage({
				type: 'success',
				message: '发布成功'
			})
			getDataList()
		})
	})
}

const handleBatchCancel = () => {
	const selectedRows = multipleTableRef.value.getSelectionRows()
	const ids = selectedRows.map(row => row.id)
	let params = {
		ids: ids
	}
	ElMessageBox.confirm('确定取消发布吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		cancelPublishApi(params).then(res => {
			ElMessage({
				type: 'success',
				message: '取消发布成功'
			})
			getDataList()
		})
	})
}
const search = () => {
	state.queryParams.pageNum = 1
	getDataList()
}

const handleReset = () => {
	state.queryForm.pageNum = 1
	state.queryForm.pageSize = 10
}
// 列表数据获取
const getDataList = async () => {
	state.dataListLoading = true
	if (state.date && state.date.length > 0) {
		state.queryForm.startPublishTime = state.date[0] + ' 00:00:00'
		state.queryForm.endPublishTime = state.date[1] + ' 23:59:59'
	} else {
		state.queryForm.startPublishTime = ''
		state.queryForm.endPublishTime = ''
	}
	await queryDataListApi(state.queryForm).then(res => {
		// console.log(res.data.list)
		state.dataListLoading = false
		state.dataList = res.data.list
		state.total = res.data.total
		state.queryForm.pageSize = res.data.pageSize
		state.queryForm.pageNum = res.data.pageNum
	})
}

const handleCurrentChange = (val: number) => {
	state.queryForm.pageNum = val
	getDataList()
}
const handleSizeChange = (val: number) => {
	state.queryForm.pageSize = val
	getDataList()
}

// 删除数据
const handleDelete = (id: any) => {
	ElMessageBox.confirm('是否删除?', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			deleteMethods(id)
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '删除失败'
			})
		})
}
const deleteMethods = async (id: any) => {
	await deleteApi(id).then(res => {
		// console.log(res.data)
		ElMessage({
			type: 'success',
			message: '删除成功'
		})
		getDataList()
	})
}

// 审批数据
const handleApproval = (row: any) => {
	let params = {
		applyStatus: '0',
		id: row.id
	}
	ElMessageBox.confirm('是否退回?', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			approvalApi(params).then(res => {
				console.log('审批数据', res.data)
				getDataList()
				// Object.assign(dataForm, res.data)
			})
		})
		.catch(() => {})
}

// 审批状态列表
const getApplyStatusList = async () => {
	await listApplyStatusApi().then(res => {
		// console.log("审批状态列表", res.data)
	})
}

interface dataObj {
	applyStatus: string
	id: string | Number
	publishStatus: string
	publishTime: string
	standardNumber: string
	traingContent: string
	trainingFileId: string
	trainingName: string
	trainingVideoFileId: string
}
const multipleSelection = ref<dataObj[]>([])
const handleSelectionChange = (val: dataObj[]) => {
	//   multipleSelection.value = val
	//   state.ids = multipleSelection.value.map(item => item.id);
}

const showFileOne = (val: any) => {
	filePreviewByName(val).then(res => {
		window.open(res.data.url)
	})
}

const showFile = (val: any, flag: Number) => {
	if (flag == 1) {
		if (val.trainingFile) {
			return val.trainingFile.fileName
		} else {
			return ''
		}
	} else {
		if (val.trainingVideoFile) {
			return val.trainingVideoFile.fileName
		} else {
			return ''
		}
	}
}

const reset = () => {
	state.date = []
	state.queryForm = {
		pageNum: 1,
		pageSize: 10,
		likeNameOrNumber: '',
		applyStatus: '',
		publishStatus: '',
		startPublishTime: '',
		endPublishTime: ''
	}
	getDataList()
}

onMounted(() => {
	getDataList()
	getApplyStatusList()
})
</script>

<style lang="scss" scoped>
.truncate-text {
	display: -webkit-box;
	-webkit-line-clamp: 4;
	-webkit-box-orient: vertical;
	overflow: hidden;
	line-height: 1.5;
}
</style>

<style>
.custom-tooltip {
	max-width: 400px;
	/* 限制最大宽度 */
	word-wrap: break-word;
	/* 允许长单词或URL换行 */
}
</style>
